package com.gitee.wsl.platform

import kotlinx.cinterop.*
import platform.posix._winmajor
import platform.posix._winminor
import platform.windows.*
import kotlin.experimental.ExperimentalNativeApi

object MingwNativePlatform:Platform{

    override val fileSeparator: String
        get() = "\\"

    override val lineSeparator: String
        get() = "\r\n"

    @OptIn(ExperimentalNativeApi::class)
    override val current: PlatformType
        get() = PlatformType.OS.Desktop.Windows(
            arch = kotlin.native.Platform.cpuArchitecture.asArch(),
            version = "$_winmajor.$_winminor",
        )

    @OptIn(ExperimentalForeignApi::class)
    val osInfo = memScoped {
        alloc<_OSVERSIONINFOW>().apply {
            dwOSVersionInfoSize = sizeOf<OSVERSIONINFOEXW>().toUInt()
        }
    }

    val osVersion: String = "${osInfo.dwMajorVersion}.${osInfo.dwMinorVersion} (Build ${osInfo.dwBuildNumber})"

    @OptIn(ExperimentalForeignApi::class)
    fun getEnvironmentVariables(): Map<String, String> {
        val environmentStrings = GetEnvironmentStringsW() ?: return emptyMap()

        val environmentVariables = mutableMapOf<String, String>()

        try {
            var envPointer: CPointer<UShortVar>? = environmentStrings
            while (envPointer != null) {
                val entry = envPointer.toKStringFromUtf16()
                if (entry.isEmpty()) {
                    break
                }

                val (key, value) = entry.split("=", limit = 2)
                environmentVariables[key] = value

                envPointer += entry.length + 1 // Move to the next entry
            }
        } finally {
            FreeEnvironmentStringsW(environmentStrings)
        }

        return environmentVariables
    }
}
